package com.juyu.miliao.api.service;


import com.juyu.miliao.api.dao.mysql.RegisterAddressDao;
import com.juyu.miliao.api.domain.RegisterAddress;
import com.juyu.miliao.common.domain.GaodeConfig;
import com.juyu.miliao.common.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jh
 * 2018/9/30
 */
@Service
@Slf4j
public class RegisterAddressService {


    @Resource
    private RegisterAddressDao registerAddressDao;

    /**
     * 高德api限制,小数点后不能超过6位
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @return string
     */
    public static String filterLocation(String longitude, String latitude) {
        if (!StringUtils.isEmpty(longitude)) {
            int index = StringUtils.indexOf(longitude, ".");
            longitude = StringUtils.substring(longitude, 0, index + 7);
        }

        if (!StringUtils.isEmpty(latitude)) {
            int index = StringUtils.indexOf(latitude, ".");
            latitude = StringUtils.substring(latitude, 0, index + 7);
        }

        return new StringBuilder(longitude).append(",").append(latitude).toString();
    }

    public void update(String longitude, String latitude, Long userId) {
        String fullAddr = "";
        String city = "";
        Map<String, Object> map = new HashMap<>(4);
        map.put("location", filterLocation(longitude, latitude));
        map.put("key", GaodeConfig.getKey());
        Response response = OkHttpUtil.getSyn(null, GaodeConfig.REGEO_URL, map);
        if (response != null && response.isSuccessful()) {
            if (response.body() != null) {
                String bodyString = null;
                try {
                    bodyString = response.body().string();
                    JSONObject jsonObject = JSONObject.fromObject(bodyString);
                    if ("1".equals(jsonObject.get("status"))) {
                        JSONObject regeocode = jsonObject.getJSONObject("regeocode");
                        fullAddr = regeocode.get("formatted_address") == null ? "" : regeocode.get("formatted_address").toString();
                        JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                        city = addressComponent.get("city") == null ? "" : addressComponent.get("city").toString();
                        if ("".equals(city) || "[]".equals(city)) {
                            city = addressComponent.get("province").toString();
                        }
                    }
                } catch (Exception e) {
                    log.error("更新RegisterAddress错误:msg:{}", e.getMessage());
                }
            }
        }

        if (!"".equals(fullAddr) && !"".equals(city)) {
            RegisterAddress addr = registerAddressDao.getRegisterAddressByUserId(userId);
            try {
                if (addr == null) {
                    addr = new RegisterAddress();
                    addr.setCity(city);
                    addr.setFullAddr(fullAddr);
                    addr.setLongitude(longitude);
                    addr.setLatitude(latitude);
                    addr.setUserId(userId);
                    registerAddressDao.saveRegisterAddress(addr, userId);
                } else {
                    addr.setLongitude(longitude);
                    addr.setLatitude(latitude);
                    addr.setCity(city);
                    addr.setFullAddr(fullAddr);
                    registerAddressDao.updateRegisterAddress(addr, userId);
                }
            } catch (Exception e) {
                log.error("更新RegisterAddress错误:msg:{}", e.getMessage());
            }
        }
    }

}
